package scanpackage.aspect;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import org.apache.http.HttpResponse;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import scanpackage.exception.AuthException;
import scanpackage.filter.HeaderHttpResponseFilter;
import scanpackage.filter.HttpRequestFilter;
import scanpackage.future.CustomFutureCallback;
import scanpackage.generator.ResponseGenerator;
import scanpackage.property.RouteProperty;
import scanpackage.router.HttpEndpointRouter;

import static io.netty.handler.codec.http.HttpResponseStatus.UNAUTHORIZED;


@Aspect
@Component
public class HandleAaspect {
    @Autowired
    private HttpRequestFilter httpRequestFilter;
    @Autowired
    private HttpEndpointRouter httpRoute;
    @Autowired
    private HeaderHttpResponseFilter httpResponseFilter;
    @Autowired
    private RouteProperty routeProperty;
    @Around("execution(* scanpackage.outbound.HttpOutboundHandler.handle(..))")
    public void handlearound(ProceedingJoinPoint joinPoint) throws Throwable{
        //获取传入参数
        Object[] args = joinPoint.getArgs();
        FullHttpRequest fullRequest= (FullHttpRequest) args[0];
        ChannelHandlerContext ctx= (ChannelHandlerContext) args[1];
        //对请求头进行自定义，通过设置"yourname"来使某些服务通过验证
        httpRequestFilter.filter(fullRequest,ctx);
        //路由获取host
        args[2]=httpRoute.route(routeProperty,fullRequest.uri());
        joinPoint.proceed(args);
    }

    @Around("execution(* scanpackage.future.CustomFutureCallback.completed(..))")
    public void handleResponseAround(ProceedingJoinPoint joinPoint) throws Throwable{
        //获取传入参数
        CustomFutureCallback customFutureCallback = (CustomFutureCallback) joinPoint.getTarget();
        Object[] args = joinPoint.getArgs();
        try {
            httpResponseFilter.filter((HttpResponse) args[0]);
            //如果没有抛异常就是证明他没有401就让方法执行
            joinPoint.proceed(args);

        }catch (AuthException authException)
        {
            authException.printStackTrace();
            FullHttpResponse response=ResponseGenerator.getResponse(UNAUTHORIZED,Unpooled.wrappedBuffer("UNAUTHORIZED".getBytes()),(HttpResponse) args[0]);
            customFutureCallback.getCtx().write(response);
            customFutureCallback.getCtx().flush();
        }
    }
}
